(ns samber.middleware
  (:require
    [samber.env :refer [defaults]]
    [samber.config :refer [env]]
    [ring.middleware.defaults :refer [site-defaults wrap-defaults]]
    [buddy.auth.middleware :refer [wrap-authentication wrap-authorization]]
    [buddy.auth.accessrules :refer [restrict]]
    [buddy.auth :refer [authenticated?]]
    [buddy.auth.backends.token :refer [jws-backend]]
    [clojure.tools.logging :as log]))

(defn on-error [request response]
  {:status 403
   :headers {}
   :body {:code 1 :msg "not authorized"}})

(defn wrap-restricted [handler]
  (restrict handler {:handler authenticated?
                     :on-error on-error}))

(def backend (jws-backend {:secret "11myvery--mmmm" :options {:alg :hs512}}))

(defn wrap-auth [handler]
  (-> handler
      (wrap-authentication backend)
      (wrap-authorization backend)))

(defn wrap-base [handler]
  (log/warn "xxxxx!!!!!")
  (-> ((:middleware defaults) handler)
      wrap-auth
      (wrap-defaults
        (-> site-defaults
            (assoc-in [:security :anti-forgery] false)))))
